package com.auction.job.core.schedule;

import com.auction.job.domain.config.SystemConfig;
import com.auction.job.domain.util.Constant;
import com.google.gson.JsonObject;
import com.google.gson.JsonParser;
import com.yisu.auction.ewf.common.spring.SpringContext;
import com.yisu.auction.ewf.common.web.HttpWebClient;
import org.quartz.JobExecutionContext;
import org.quartz.JobExecutionException;

import java.util.HashMap;
import java.util.Map;

/**
 * Created by nichole on 2017/9/5.
 */
public class DupBuyJob extends BaseJob {
    private String prizeId;
    private String userId;

    public void setPrizeId(String prizeId) {
        this.prizeId = prizeId;
    }

    public void setUserId(String userId) {
        this.userId = userId;
    }

    @Override
    protected void executeInternal(JobExecutionContext jobExecutionContext) throws JobExecutionException {
        SystemConfig systemConfig = SpringContext.getBean("systemConfig");
        Map<String, String> params = new HashMap<>();
        params.put("memberId", userId);
        params.put("prizeId", prizeId);
        params.put("buyCount", "1");
        params.put("auctionType", "2");//连续拍
        sleep();
        String result = HttpWebClient.post(systemConfig.getCreateOrderUrl(), params);
        LOG.info("duplication purchase response for prize[{}] with user[{}]: {}", new String[]{prizeId, userId, result});

        JsonObject jsonObject= new JsonParser().parse(result).getAsJsonObject();
        int errorCode = jsonObject.get("errorCode").getAsInt();
        switch (errorCode) {
            case Constant.PURCHASE_SUCCESS:
                LOG.info("successfully purchase for prize[{}]", prizeId);
                break;
            case Constant.WILL_OPEN_PRIZE:
                LOG.info("successfully purchase for prize[{}] and will open prize.", prizeId);
                QuartzManager.addOpenPrizeJob(prizeId);
                break;
            case Constant.PRIZE_END:
            case Constant.USER_BUY_END:
                QuartzManager.removeDupBuyJob(prizeId);
                LOG.warn("manually stop the prize[{}]", prizeId);
                break;
            default:
                LOG.error("failed to purchase for prize[{}], error code[{}], error message[{}]",
                        new String[]{prizeId, String.valueOf(errorCode), jsonObject.get("errorMessage").getAsString()});
                break;
        }
    }
}
